
import javafx.scene.input.Mnemonic;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.prefs.Preferences;
import javax.imageio.ImageIO;
import javax.swing.*;
/*
    The this main class is a little
    disorganized, and as of right now
    I don't feel like cleaning it up.
 */

public class GUIMain extends JFrame
{
    /*
        This section is for declaring
        important pieces of the GUI
     */
    GUIAbout guiAbout = new GUIAbout();
    ShortAStock shortAStock = new ShortAStock();
    PennyStock pennyStock = new PennyStock();

    //for preferences
    public final Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
    private Action save;
    private KeyStroke keySave = KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK);
    private Action reset;
    private KeyStroke keyReset = KeyStroke.getKeyStroke(KeyEvent.VK_R, Event.CTRL_MASK);
    private Action actionExit;
    private KeyStroke keyExit = KeyStroke.getKeyStroke(KeyEvent.VK_E, Event.CTRL_MASK);
    private Action actionAbout;
    private KeyStroke keyAbout = KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK);

    //for calculations
    private double stocks = 0;
    private double cent = 0;

    //menu bar
    private JMenuBar menuBar;
    private JMenu file;
    private JMenuItem exit;
    private JMenuItem savePref;
    private JMenuItem resetPref;
    private JMenu documentation;
    private JMenuItem about;

    //Strings are for identifying panels for combo box
    final static String makeMoneyPanel = "Make Money";
    final static String shortAStockPanel = "Short a Stock";
    final static String pennyStockPanel = "Penny Stocks";

    //gridbag variable c and inset declaration
    private GridBagConstraints c;
    Insets m = new Insets(2,10,2,10);

    //panel setup
    private JPanel container;
    private JPanel cards;
    private JPanel card1;
    private JPanel card2;
    private JPanel card3;
    private JPanel card1LeftPanel;
    private JPanel card1RightPanel;

    //GUI components for card1
    private JLabel stockBrokerComish;
    private JTextField stockBrokerComishField;
    private JLabel investing;
    private JTextField investingField;
    private JLabel priceOfStock;
    private JTextField priceOfStockField;
    private JLabel make;
    private JTextField makeField;
    private JButton purchaseAmountB;
    private JLabel stockBuying;
    private JTextField stockBuyingField;
    private JButton generateB;
    private JButton clear;

    public GUIMain()
    {
        //Date buildDate = new Date();
        //DateFormat dFormat = new SimpleDateFormat("yyyyMdd");

        this.setTitle("Stock Profit Calculator 1.0"); //+dFormat.format(buildDate));
        this.setMinimumSize(new Dimension(550, 400));
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setResizable(false);

        BufferedImage image = null;
        try {
            image = ImageIO.read(getClass().getResource("KDG_Logo_small.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        setIconImage(image);

        shortAStock.createPanel();
        pennyStock.createPanel();
        guiAbout.CreateBody();
        guiAbout.setLocationRelativeTo(null);

        //this is to bind ctrl+s to save preferences
        save = new AbstractAction("Save") {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveSettings();
            }
        };

        reset = new AbstractAction("Reset") {
            @Override
            public void actionPerformed(ActionEvent e) {
                resetSettings();
            }
        };

        actionExit = new AbstractAction("Exit") {
            @Override
            public void actionPerformed(ActionEvent e) {
                exit();
            }
        };

        actionAbout = new AbstractAction("About") {
            @Override
            public void actionPerformed(ActionEvent e) {
                guiAbout.setVisible(true);
            }
        };

        //set short a stocks settings
        shortAStock.makeField.setText(prefs.get("shortMake", null));
        shortAStock.ownField.setText(prefs.get("shortOwn", null));
        shortAStock.stocksField.setText(prefs.get("shortStocks", null));
        shortAStock.declineField.setText(prefs.get("shortDecline", null));

        //set penny stocks settings
        pennyStock.comishField.setText(prefs.get("pennyComish", null));
        pennyStock.perShareField.setText(prefs.get("pennyShare", null));
        pennyStock.stockPriceField.setText(prefs.get("pennyStock", null));
        pennyStock.investingField.setText(prefs.get("pennyInvest", null));
        pennyStock.makeField.setText(prefs.get("pennyMake", null));
    }

    //create the main GUI with labels and text fields
    public void createMainScreen()
    {
        //create menu bar
        menuBar = new JMenuBar();
        file = new JMenu("File");

        savePref = new JMenuItem(save);
        savePref.setText("Save Preferences");
        savePref.addActionListener(new EventListener());
        savePref.getActionMap().put("save", save);
        savePref.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySave, "save");
        savePref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
        file.add(savePref);
        resetPref = new JMenuItem(reset);
        resetPref.setText("Reset Preferences");
        resetPref.addActionListener(new EventListener());
        resetPref.getActionMap().put("reset", reset);
        resetPref.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyReset, "reset");
        resetPref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK));
        file.add(resetPref);
        exit = new JMenuItem(actionExit);
        exit.setText("Exit");
        exit.getActionMap().put("exit", actionExit);
        exit.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyExit, "exit");
        exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
        exit.addActionListener(new EventListener());
        file.add(exit);
        documentation = new JMenu("Documentation");
        about = new JMenuItem(actionAbout);
        about.setText("About");
        about.getActionMap().put("about", actionAbout);
        about.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyAbout, "about");
        about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
        about.addActionListener(new EventListener());
        documentation.add(about);
        menuBar.add(file);
        menuBar.add(documentation);
        this.setJMenuBar(menuBar);

        c = new GridBagConstraints();

        //create the cards & main panel
        //the cards are basically different panels relating
        //to the strings declared at the beginning of this file
        container = new JPanel(new BorderLayout());
        card1 = new JPanel(new BorderLayout());
        card2 = new JPanel(new BorderLayout());
        card3 = new JPanel(new BorderLayout());

        //card 1, left panel setup
        card1LeftPanel = new JPanel(new GridBagLayout());

        stockBrokerComish = new JLabel("<html>How much is your stock broker's<br> commission?</html>");
        stockBrokerComishField = new JTextField();
        stockBrokerComishField.addActionListener(new EventListener());
        stockBrokerComishField.setText(prefs.get("comish", null));
        investing = new JLabel("How much are you investing?");
        investingField = new JTextField();
        investingField.addActionListener(new EventListener());
        investingField.setText(prefs.get("invest", null));
        priceOfStock = new JLabel("What is the price of the stock?");
        priceOfStockField = new JTextField();
        priceOfStockField.addActionListener(new EventListener());
        priceOfStockField.setText(prefs.get("stockPrice", null));
        make = new JLabel("How much do you want to make?");
        makeField = new JTextField();
        makeField.addActionListener(new EventListener());
        makeField.setText(prefs.get("make", null));

        c.insets = m;
        c.gridx = 1;
        c.gridy = 0;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(stockBrokerComish, c);

        c.gridx = 1;
        c.gridy = 3;
        c.ipadx = 100;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(stockBrokerComishField, c);

        c.gridx = 1;
        c.gridy = 5;
        m = new Insets(15,10,2,10);
        c.insets = m;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(investing, c);

        c.gridx = 1;
        c.gridy = 7;
        c.ipadx = 100;
        m = new Insets(2,10,2,10);
        c.insets = m;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(investingField, c);

        c.gridx = 1;
        c.gridy = 9;
        m = new Insets(15,10,2,10);
        c.insets = m;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(priceOfStock, c);

        c.gridx = 1;
        c.gridy = 11;
        c.ipadx = 100;
        m = new Insets(2,10,2,10);
        c.insets = m;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(priceOfStockField, c);

        c.gridx = 1;
        c.gridy = 13;
        m = new Insets(15,10,2,10);
        c.insets = m;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(make, c);

        c.gridx = 1;
        c.gridy = 15;
        c.ipadx = 100;
        m = new Insets(2,10,2,10);
        c.insets = m;
        c.anchor = GridBagConstraints.WEST;
        card1LeftPanel.add(makeField, c);

        card1.add(card1LeftPanel, BorderLayout.WEST);

        //card 1, middle filler panel
        JPanel midFill = new JPanel();
        card1.add(midFill, BorderLayout.CENTER);

        //card 1, right panel setup
        card1RightPanel = new JPanel(new GridBagLayout());

        purchaseAmountB = new JButton("Click Me");
        purchaseAmountB.addActionListener(new EventListener());
        purchaseAmountB.setToolTipText("<html>Must fill out stock broker commission, how much<br>you are investing, and the price of the stock for<br>this to become active</html>");
        purchaseAmountB.setText(prefs.get("clickMe", "Click Me"));
        stockBuying = new JLabel("How many stocks are you purchasing?");
        stockBuying.setEnabled(false);
        stockBuyingField = new JTextField();
        stockBuyingField.setEnabled(false);
        stockBuyingField.addActionListener(new EventListener());
        generateB = new JButton("Generate");
        generateB.setEnabled(false);
        generateB.addActionListener(new EventListener());
        clear = new JButton("Clear");
        clear.addActionListener(new EventListener());

        c.gridx = 1;
        c.gridy = 0;
        c.ipadx = 0;
        m = new Insets(2,10,25,10);
        c.insets = m;
        c.anchor = GridBagConstraints.EAST;
        card1RightPanel.add(purchaseAmountB, c);

        c.gridx = 1;
        c.gridy = 1;
        c.ipadx = 0;
        m = new Insets(2,10,2,10);
        c.insets = m;
        c.anchor = GridBagConstraints.EAST;
        card1RightPanel.add(stockBuying, c);

        c.gridx = 1;
        c.gridy = 2;
        c.ipadx = 100;
        c.anchor = GridBagConstraints.EAST;
        card1RightPanel.add(stockBuyingField, c);

        c.gridx = 1;
        c.gridy = 3;
        c.ipadx = 0;
        c.anchor = GridBagConstraints.EAST;
        card1RightPanel.add(generateB, c);

        c.gridx = 1;
        c.gridy = 4;
        m = new Insets(70,10,5,10);
        c.insets = m;
        c.anchor = GridBagConstraints.EAST;
        card1RightPanel.add(clear, c);

        card1.add(card1RightPanel, BorderLayout.EAST);

        //card 2 setup
        card2.add(shortAStock, BorderLayout.PAGE_START);

        //card 3 setup
        card3.add(pennyStock, BorderLayout.PAGE_START);

        //main card panel holding cards
        cards = new JPanel(new CardLayout());
        cards.add(card1, makeMoneyPanel);
        cards.add(card2, shortAStockPanel);
        cards.add(card3, pennyStockPanel);




        //combobox pane and combobox setup
        JPanel comboBoxPane = new JPanel();
        String comboBoxItems[] = { makeMoneyPanel, shortAStockPanel, pennyStockPanel };
        JComboBox cb = new JComboBox(comboBoxItems);
        cb.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                CardLayout cl = (CardLayout) (cards.getLayout());
                cl.show(cards, (String) e.getItem());
            }
        });
        comboBoxPane.add(cb);

        container.add(comboBoxPane, BorderLayout.PAGE_START);
        container.add(cards, BorderLayout.CENTER);

        this.add(container);
        this.pack();
    }

    //event handlers
    class EventListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if(e.getSource().equals(exit))
            {
                exit();
            }
            if(e.getSource().equals(savePref))
            {
                saveSettings();
            }
            if(e.getSource().equals(resetPref))
            {
                resetSettings();
            }
            if(e.getSource().equals(purchaseAmountB))
            {
                try{
                    stocks = (Double.parseDouble(investingField.getText()) - Double.parseDouble(stockBrokerComishField.getText())) / Double.parseDouble(priceOfStockField.getText());
                    purchaseAmountB.setText("You can purchase "+Math.floor(stocks)+ " stocks");
                    generateB.setEnabled(true);
                    stockBuyingField.setEnabled(true);
                    stockBuying.setEnabled(true);
                }catch(Exception ex){
                    JOptionPane.showMessageDialog(rootPane, "<html>You must properly fill out the broker's commission,<br/> how much you're investing, and the price of<br/>"
                            +"stock text fields before you can hit this button!</html>");
                }
            }
            if(e.getSource().equals(generateB))
            {
                double formatted;
                double formatted2;
                double formatted3;

                try {
                    cent = Double.parseDouble(makeField.getText()) / Double.parseDouble(stockBuyingField.getText());
                    DecimalFormat threeDigits = new DecimalFormat("###0.000");
                    formatted = Double.valueOf(threeDigits.format(cent));

                    formatted2 = Double.valueOf(threeDigits.format(Double.parseDouble(priceOfStockField.getText()) + cent));

                    formatted3 = Double.valueOf(threeDigits.format(Double.parseDouble(stockBrokerComishField.getText()) * 2));

                    if (cent < 0)
                        JOptionPane.showMessageDialog(rootPane, "I had no idea negative numbers equaled a profit!");
                    else
                    {
                        JOptionPane.showMessageDialog(rootPane, "<html>You need about a $" + formatted + " increase to make your goal for the day."
                                + "<BR/>Sell the stock at $" + formatted2 + " to make your goal."
                                + "<br/>You will spend $" + formatted3 + " in commission fees on 1 buy and sell.</html>");
                    }
                } catch (Exception evt) {
                    JOptionPane.showMessageDialog(rootPane, "All text fields must be in a proper number format!", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
            if(e.getSource().equals(clear))
            {
                stockBrokerComishField.setText(null);
                investingField.setText(null);
                priceOfStockField.setText(null);
                makeField.setText(null);
                purchaseAmountB.setText("Click Me");
                stockBuyingField.setText(null);
                stockBuying.setEnabled(false);
                generateB.setEnabled(false);
            }
            if(e.getSource().equals(about))
            {
                guiAbout.setVisible(true);
            }
        }
    }

    public void saveSettings()
    {
        //main card settings
        prefs.put("comish", stockBrokerComishField.getText());
        prefs.put("invest", investingField.getText());
        prefs.put("stockPrice", priceOfStockField.getText());
        prefs.put("make", makeField.getText());
        prefs.put("clickMe", purchaseAmountB.getText());

        //short a stock settings
        prefs.put("shortMake", shortAStock.makeField.getText());
        prefs.put("shortOwn", shortAStock.ownField.getText());
        prefs.put("shortStocks", shortAStock.stocksField.getText());
        prefs.put("shortDecline", shortAStock.declineField.getText());

        //penny stock settings
        prefs.put("pennyComish", pennyStock.comishField.getText());
        prefs.put("pennyShare", pennyStock.perShareField.getText());
        prefs.put("pennyStock", pennyStock.stockPriceField.getText());
        prefs.put("pennyInvest", pennyStock.investingField.getText());
        prefs.put("pennyMake", pennyStock.makeField.getText());
    }

    public void resetSettings()
    {
        //main card reset settings
        prefs.remove("comish");
        prefs.remove("invest");
        prefs.remove("stockPrice");
        prefs.remove("make");
        prefs.remove("clickMe");

        stockBrokerComishField.setText(null);
        investingField.setText(null);
        priceOfStockField.setText(null);
        makeField.setText(null);
        purchaseAmountB.setText("Click Me");

        //shortAStock card reset settings
        prefs.remove("shortMake");
        prefs.remove("shortOwn");
        prefs.remove("shortStocks");
        prefs.remove("shortDecline");

        shortAStock.makeField.setText(null);
        shortAStock.ownField.setText(null);
        shortAStock.stocksField.setText(null);
        shortAStock.declineField.setText(null);

        //penny stock card reset settings
        prefs.remove("pennyComish");
        prefs.remove("pennyShare");
        prefs.remove("pennyStock");
        prefs.remove("pennyInvest");
        prefs.remove("pennyMake");

        pennyStock.comishField.setText(null);
        pennyStock.perShareField.setText(null);
        pennyStock.stockPriceField.setText(null);
        pennyStock.investingField.setText(null);
        pennyStock.makeField.setText(null);
    }

    public void exit()
    {
        System.exit(0);
    }

    //let's get the ball rolling!!
    public static void main(String[] args)
    {
        GUIMain run = new GUIMain();
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            try {
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
            } catch (Exception e2) {
                ;
            }
        }

        run.createMainScreen();
        run.setVisible(true);
    }
}//end class